//
//  NSDate-Extension.swift
//  WeiBo
//
//  Created by LTX on 2016/11/25.
//  Copyright © 2016年 LTX. All rights reserved.
//

import Foundation

extension NSDate {
    
   class func createDateString(createAtStr : String) -> String {
        // 创建时间格式对象
        let fmt = DateFormatter();
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyy"
        fmt.locale = Locale(identifier: "en")
    
        // 将字符串时间转出NSDate类型
        guard  let createDate = fmt.date(from: createAtStr) else{
        return ""
        }
    
        //创建当前时间
        let nowDate = NSDate()
    
        //计算创建时间和当前时间的 时间差
        let interval = Int(nowDate.timeIntervalSince(createDate))
    
        //对时间间隔处理
    
        if interval < 60 {
            return "刚刚"
        }
    
    
    // 5.2.59分钟前
    if interval < 60 * 60 {
        return "\(interval / 60)分钟前"
    }
    
    if interval < 60 * 60 * 24 {
        return "\(interval / (60 * 60))小时前"
    }
    
    
        //创建日历对象
       let calendar = NSCalendar.current
    
        if calendar.isDateInYesterday(createDate) {
            fmt.dateFormat = "昨天 HH:mm"
            let timeStr = fmt.string(from: createDate)
            return timeStr
            
        }
    
    
    // 5.6.处理一年之内: 02-22 12:22
//    let cmps = calendar.components(.Year, fromDate: createDate, toDate: nowDate, options: [])
    
    let cmps = (calendar as NSCalendar).components(.year, from: createDate, to: nowDate as Date, options: [])
    

    if cmps.year! < 1 {
        fmt.dateFormat = "MM-dd HH:mm"
        let timeStr = fmt.string(from: createDate)
        return timeStr
    }
    
    
    
    // 5.7.超过一年: 2014-02-12 13:22
    fmt.dateFormat = "yyyy-MM-dd HH:mm"
    let timeStr = fmt.string(from: createDate)
    return timeStr
    }



}
